﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;


namespace mmoss.classes
{
    public class z_KeystrokeMessageFilter : System.Windows.Forms.IMessageFilter
    {
        public delegate void CCScannedGood(CCCard l_Card);
        public delegate void CardScannedBad(string l_message);
        public delegate void LicenseScannedGood(DriversLicense l_License);
        public event CCScannedGood CCScanned;
        public event LicenseScannedGood LicenseScanned;
        public event CardScannedBad CardBadScan;
        public string KeyBuffer = "";
        Timer KeyTimeOut = new Timer();
        private bool ScanInProgress = false;

        public z_KeystrokeMessageFilter()
        {
            KeyTimeOut.Tick += new EventHandler(KeyTimeOut_Tick);
        }

        void KeyTimeOut_Tick(object sender, EventArgs e)
        {

            //timed out
            ScanInProgress = false;
            KeyTimeOut.Enabled = false;
            KeyTimeOut.Stop();
            //show buffer
            //MessageBox.Show("buffer=" + KeyBuffer + "last key = " + ((int)KeyBuffer.Substring(KeyBuffer.Length - 1, 1).ToCharArray()[0]).ToString());
            //create the appropropriate object type
            //todo - make this more generic a routing

        }

        #region Implementation of IMessageFilter
        public bool PreFilterMessage(ref Message m)
        {
            if ((m.Msg == 256 /*0x0100*/))
            {
                switch (((int)m.WParam) | ((int)Control.ModifierKeys))
                {
                    case (int)(Keys.D5 | Keys.Shift):
                        KeyTimeOut.Interval = 5000;
                        KeyTimeOut.Start();
                        KeyBuffer = "";
                        ScanInProgress = true;
                        return false;
                        break;
                    case 13:
                        //carriage return
                        ScanInProgress = false;
                        return false;
                        //MessageBox.Show("buffer=" + KeyBuffer);
                        break;
                }
                if (ScanInProgress)
                {
                    //KeyBuffer += (((int)m.WParam) | ((int)Control.ModifierKeys)).ToString()+ "|";
                    KeyBuffer += ((int)m.WParam).ToString() + "|";
                    KeyTimeOut.Stop();
                    KeyTimeOut.Start();
                    return false;
                }
            }
            return false;
        }
    }
}
#endregion